#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/2/12 9:25
# @Author  : Fancy
# @FileName: dm.py
# @Software: PyCharm
# @runstate    ：
import dmPython
from db_compare.clients.base import BaseClient

class DMClient(BaseClient):
    def __init__(self, config):
        self.config = config
        print(f"DMClient 初始化, config: {self.config}")
    """dm 客户端实现"""
    def get_conn(self):
        try:
            # 使用 connect_args 中的配置信息进行连接
            connection = dmPython.connect (
                host=self.config.connect_args["host"],
                user=self.config.connect_args["user"],
                password=self.config.connect_args["password"],
                port=int (self.config.connect_args["port"])
            )
            #print (f"成功连接到 DM 数据库 {self.config.connect_args['database']}")
            return connection
        except Exception as e:
            print (f"DM 连接失败: {e}")
            raise
        except Exception as e:
            print (f"连接失败: {e}")
            raise


    def fetch_stream (self, table: str, batch_size: int = 1000):
        """流式获取数据"""
        offset = 0
        conn = self.get_conn ()
        try:
            while True:
                with conn.cursor () as cursor:
                    cursor.execute (f"SELECT * FROM {table} LIMIT {batch_size} OFFSET {offset}")
                    batch = cursor.fetchall ()
                    if not batch:
                        break
                    yield batch
                    offset += batch_size
                    #print (f"获取表 {table} 的数据流，每批 {batch_size} 条")
        finally:
            conn.close ()